//
//  ClubTopicDetailViewController.swift
//  77Club
//
//  Created by Apple on 2024/12/26.
//

import UIKit
import ZLPhotoBrowser

class ClubTopicDetailViewController: ClubBaseViewController, RaeAnimationProtocol {
//
    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let titleLabel = UIIconButton(style: .leading(itemSpace: 0))
    private let browseLabel = c_make_ex(UILabel.self)
        .color("#AFB1B3").font(12.font_medium).end()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubDynamicListCell.self,ClubSquareForumCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 306.0.Scale
        return tableView
    }()
    
    private var dataSource = [ClubSquareTopicModel]()
    private var pageIndex = 1
    private var playingIndexPath: IndexPath?
    private var currentVC = true
    
    var topicId: String = "" {
        didSet{
            self.loadData()
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        currentVC = true
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)

        currentVC = false
        NotificationCenter.default.post(name: .stopDynamicAudioPlayer, object: nil)
        NotificationCenter.default.post(name: .stopForumAudioPlayer, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            backButton
            titleLabel
            browseLabel
            tableView
        }
        
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.leading(16.0.Scale).top(.navi_height).height(22.0.Scale)
        browseLabel.leading(16.0.Scale).top(.navi_height + 25.0.Scale)
        tableView.fillContainer().top(.navi_height + 45.0.Scale)
        
        titleLabel.style { v in
            v.setImage("Topic_detail_titleTag".toImage, for: .normal)
            v.iconSize = CGSize(width: 22.0.Scale, height: 22.0.Scale)
            v.setTitleColor(.black, for: .normal)
            v.titleLabel?.font = 16.font_semiBold
            v.contentHorizontalAlignment = .leading
            v.isUserInteractionEnabled = false
        }
        
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateNewData), name: .updateDynamicListData, object: nil)
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubTopicDetailViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = self.dataSource[indexPath.row]
        if model.type == 1 {
            //动态
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicListCell", for: indexPath) as! ClubDynamicListCell
            cell.topicModel = model.data
            cell.jumpToDetail = { id in
                let detailController = ClubDynamicDetailViewController()
                detailController.dynamicID = id
                self.navigationController?.pushViewController(detailController, animated: true)
            }
            cell.didSelectImage = { index,images in
                self.selectImage(index: index, images: images)
            }
            cell.didSelectVideo = { url in
                self.selectVideo(url: url)
            }
            cell.toGameDetailVC = { gid in
                let detailVC = ClubGameDetailViewController()
                detailVC.gameId = gid
                self.navigationController?.pushViewController(detailVC, animated: true)
            }
            cell.toTopicDetailVC = { topicId in
                let detailVC = ClubTopicDetailViewController()
                detailVC.topicId = topicId
                self.navigationController?.pushViewController(detailVC, animated: true)
            }
            cell.showTopicMoreView = { md in
                let moreView = ClubMoreView()
                moreView.uid_des = md.uid_des
                moreView.reportBlock = {
                    if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                        let reportVC = ClubReportViewController()
                        reportVC.dynamicID = md.id
                        reportVC.updateDataBlock = {
                            self.loadNewData()
                        }
                        self.present(reportVC, animated: true)
                    }else{
                        self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                    }
                }
                moreView.delBlock = {
                    Task{
                        let res = await self.network.request(.delDynamic(id: md.id))
                        if res.isSuccess {
                            "删除成功".toast_success
                            self.loadNewData()
                        }
                    }
                }
                moreView.copyShareBlock = { type in
                    self.shareDetail(type: type, shareUrl: md.share_url)
                }
                self.entryAnimate.animation(show: moreView)
            }
            cell.otherUserInfoVC = { uid in
                if uid.count > 0 {
                    if let user_id = UserDefaultsManager.getString(forKey: .uid), user_id.count > 0, user_id == uid {
                        let otherVC = ClubMineInfoViewController()
                        self.navigationController?.pushViewController(otherVC, animated: true)
                    }else{
                        let otherVC = ClubOtherInfoViewController()
                        otherVC.uid = uid
                        otherVC.updateBlock = {
                            self.loadNewData()
                        }
                        self.navigationController?.pushViewController(otherVC, animated: true)
                    }
                }
            }
            return cell
        }else{
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareForumCell", for: indexPath) as! ClubSquareForumCell
            cell.topicModel = model.data
            cell.zanButtonClick = { postId in
                self.likePost(ID: postId)
            }
            cell.jumpToDetail = {postId, uid in
                self.toDetailVC(newId: postId, uid: uid)
            }
            cell.didSelectImage = { index,images in
                self.selectImage(index: index, images: images)
            }
            cell.didSelectVideo = { url in
                self.selectVideo(url: url)
            }
            cell.toGameDetailVC = { gid in
                let detailVC = ClubGameDetailViewController()
                detailVC.gameId = gid
                self.navigationController?.pushViewController(detailVC, animated: true)
            }
            cell.toTopicDetailVC = { topicId in
                let detailVC = ClubTopicDetailViewController()
                detailVC.topicId = topicId
                self.navigationController?.pushViewController(detailVC, animated: true)
            }
            cell.showTopicMoreView = { md in
                let moreView = ClubMoreView()
                moreView.uid_des = md.uid_des
                moreView.reportBlock = {
                    if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                        let reportVC = ClubReportViewController()
                        reportVC.isShequ = true
                        reportVC.dynamicID = md.id
                        self.present(reportVC, animated: true)
                    }else{
                        self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                    }
                }
                moreView.delBlock = {
                    Task{
                        let res = await self.network.request(.delPost(postID: md.id))
                        if res.isSuccess {
                            "删除成功".toast_success
                            self.loadNewData()
                        }
                    }
                }
                moreView.copyShareBlock = { type in
                    self.shareDetail(type: type, shareUrl: md.share_url, titile: md.title, content: md.content)
                }
                self.entryAnimate.animation(show: moreView)
            }
            cell.otherUserInfoVC = { uid in
                if uid.count > 0 {
                    if let user_id = UserDefaultsManager.getString(forKey: .uid), user_id.count > 0, user_id == uid {
                        let otherVC = ClubMineInfoViewController()
                        self.navigationController?.pushViewController(otherVC, animated: true)
                    }else{
                        let otherVC = ClubOtherInfoViewController()
                        otherVC.uid = uid
                        otherVC.updateBlock = {
                            self.loadNewData()
                        }
                        self.navigationController?.pushViewController(otherVC, animated: true)
                    }
                }                
            }
            
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = self.dataSource[indexPath.row]
        if model.type == 1 {
            
            guard let dynamicId = model.data?.id else { return }
            let detailController = ClubDynamicDetailViewController()
            detailController.dynamicID = dynamicId
            detailController.updateDataBlock = {
                self.loadNewData()
            }
            self.navigationController?.pushViewController(detailController, animated: true)
        }else{
            
            if model.data?.uid != "0" {
                //用户
                let detailVC = ClubSquareForumDetailViewController()
                detailVC.postID = model.data?.id ?? "0"
//                detailVC.pid = self.communityId
//                detailVC.communityModel = self.model
                detailVC.likeBlock = {
                    self.loadNewData()
                }
                detailVC.updateDataBlock = {
                    self.loadNewData()
                }
                self.navigationController?.pushViewController(detailVC, animated: true)
            }else{
                //官方
                let detailVC = ClubForumDetailViewController()
                detailVC.newId = model.data?.id ?? "0"
                detailVC.likeBlock = {
                    self.loadNewData()
                }
                self.navigationController?.pushViewController(detailVC, animated: true)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if let visibleCells = tableView.visibleCells as? [ClubDynamicListCell] {
            // 获取 TableView 的中心位置
            let tableViewCenter = tableView.bounds.size.height / 2 + tableView.contentOffset.y

            for cell in visibleCells {
                guard let indexPath = tableView.indexPath(for: cell) else { continue }
                let cellCenterY = cell.center.y

                // 判断 Cell 中心是否接近 TableView 中心
                if tableView.contentOffset.y == 0 {
                    loadFirstVideo()
                }
                if abs(cellCenterY - tableViewCenter) < 50 { // 设定 50 为接近程度的阈值
                    if playingIndexPath != indexPath {
                        playingIndexPath = indexPath
                        cell.playVideo()  // 播放视频
                    }
                } else {
                    if playingIndexPath == indexPath {
                        cell.pauseVideo()  // 暂停视频
                        playingIndexPath = nil
                    }
                }
            }
        }
        
        if let visibleCells = tableView.visibleCells as? [ClubSquareForumCell] {
            // 获取 TableView 的中心位置
            let tableViewCenter = tableView.bounds.size.height / 2 + tableView.contentOffset.y

            for cell in visibleCells {
                guard let indexPath = tableView.indexPath(for: cell) else { continue }
                let cellCenterY = cell.center.y

                // 判断 Cell 中心是否接近 TableView 中心
                if tableView.contentOffset.y == 0 {
                    loadFirstVideo()
                }
                if abs(cellCenterY - tableViewCenter) < 50 { // 设定 50 为接近程度的阈值
                    if playingIndexPath != indexPath {
                        playingIndexPath = indexPath
                        cell.playVideo()  // 播放视频
                    }
                } else {
                    if playingIndexPath == indexPath {
                        cell.pauseVideo()  // 暂停视频
                        playingIndexPath = nil
                    }
                }
            }
        }
    }
}


//MARK: action
extension ClubTopicDetailViewController {
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func shareDetail(type: Int, shareUrl: String) {
        if type == 3 {
            ClubGlobalTool.shared.shareToQQ(title: ClubGlobalTool.shared.dynamicShareTitle, description: ClubGlobalTool.shared.dynamicShareDes, imageUrl: "https://www.77.top/static/ios_logo.jpg", url: shareUrl)
        }else if type == 4 {
            "分享口令已复制成功".toast_success
            UIPasteboard.general.string = shareUrl
        }else{
            ClubGlobalTool.shared.shareToWechat(title: ClubGlobalTool.shared.dynamicShareTitle, des: ClubGlobalTool.shared.dynamicShareDes, image: "AppIcon".toImage!, shareUrl: shareUrl, shareType: type)
        }
    }
    
    private func loadFirstVideo(){
        
        if currentVC {
           
            if self.dataSource.count > 0 {
                guard let md = self.dataSource[0].data else { return }
                if md.video.count > 0 {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        let indexPath = IndexPath(row: 0, section: 0)
                        self.playingIndexPath = indexPath
                        if let cell = self.tableView.cellForRow(at: indexPath) as? ClubDynamicListCell {
                            cell.playVideo()  // 播放视频
                        }
                        if let cell = self.tableView.cellForRow(at: indexPath) as? ClubSquareForumCell {
                            cell.playVideo()  // 播放视频
                        }
                    }
                }
            }            
        }
    }
    
    private func likePost(ID: String){
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            Task{
                ToastUtil.show()
                let _ = await self.network.request(.likeStrategyPost(pid: ID, puid: "", type: "0"))
                ToastUtil.dismiss()
                "点赞成功".toast_success
                self.loadNewData()
            }
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
        
    }
    
    private func toDetailVC(newId: String, uid: String){
        
        if uid != "0" {
            //用户
            let detailVC = ClubSquareForumDetailViewController()
            detailVC.postID = newId
//            detailVC.pid = self.communityId
//            detailVC.communityModel = self.model
            detailVC.likeBlock = {
                self.loadNewData()
            }
            detailVC.updateDataBlock = {
                self.loadNewData()
            }
            self.navigationController?.pushViewController(detailVC, animated: true)
        }else{
            //官方
            let detailVC = ClubForumDetailViewController()
            detailVC.newId = newId
            detailVC.likeBlock = {
                self.loadNewData()
            }
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
    }
    
    private func shareDetail(type: Int, shareUrl: String, titile: String, content: String) {
        if type == 3 {
            ClubGlobalTool.shared.shareToQQ(title: titile, description: content, imageUrl: "https://www.77.top/static/ios_logo.jpg", url: shareUrl)
        }else if type == 4 {
            "分享口令已复制成功".toast_success
            UIPasteboard.general.string = shareUrl
        }else{
            ClubGlobalTool.shared.shareToWechat(title: titile, des: content, image: "AppIcon".toImage!, shareUrl: shareUrl, shareType: type)
        }
    }
}

//MARK: data
extension ClubTopicDetailViewController {
    
    func loadData() {

        Task {
            let res = await network.requestMore(.squareTopicList(page: pageIndex, topicID: topicId),type: ClubSquareTopicListModel.self)
            tableView.refresh_end()
            self.dataSource.removeAll()
            if res.isSuccess, let model = res.model {
                if let models = model.data, models.count > 0 {
                    for var mdd in models {
                        guard let md = mdd.data else { return }
                        var mod = md
                        var itemSize: CGSize = .zero
                        if md.video.count > 0 {
                            itemSize = .zero
                        }else if md.img.count == 1 {
                            itemSize = CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
                        }else if md.img.count == 2 {
                            itemSize = CGSize (width: (CGFloat.screenWidth - 106.0.Scale)/2.0, height: 83.0.Scale)
                        }else if md.img.count > 2 {
                            let w = (CGFloat.screenWidth - 110.0.Scale)/3
                            itemSize = CGSize (width: w, height: w)
                        }else{
                            itemSize = .zero
                        }
                        mod.itemSize = itemSize
                        mdd.data = mod
                        self.dataSource.append(mdd)
                    }
                }
                if let subject = model.subject {
                    self.titleLabel.setTitle(subject.name, for: .normal)
                    self.browseLabel.text = subject.views + "浏览"
                }
                self.tableView.reloadData()
                self.loadFirstVideo()
            }
        }
    }
    
    @objc func loadNewData() -> () {
        pageIndex = 1
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        pageIndex += 1
        Task {
            let res = await network.requestMore(.squareTopicList(page: pageIndex, topicID: ""),type: ClubSquareTopicListModel.self)
            if res.isSuccess, let model = res.model {
                if let models = model.data, models.count > 0 {
//                    self.dataSource.append(contentsOf: models)
                    for var mdd in models {
                        guard let md = mdd.data else { return }
                        var mod = md
                        var itemSize: CGSize = .zero
                        if md.video.count > 0 {
                            itemSize = .zero
                        }else if md.img.count == 1 {
                            itemSize = CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
                        }else if md.img.count == 2 {
                            itemSize = CGSize (width: (CGFloat.screenWidth - 106.0.Scale)/2.0, height: 83.0.Scale)
                        }else if md.img.count > 2 {
                            let w = (CGFloat.screenWidth - 110.0.Scale)/3
                            itemSize = CGSize (width: w, height: w)
                        }else{
                            itemSize = .zero
                        }
                        mod.itemSize = itemSize
                        mdd.data = mod
                        self.dataSource.append(mdd)
                    }
                }else{
                    tableView.refresh_end(true)
                }
                self.tableView.reloadData()
            }
        }
    }
    
    @objc private func updateNewData(){
        loadNewData()
    }
}
